package com.zsgeek.wisdchain.qutu.view.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hbw020.androidcustomizedialogandpopupwindow.presenter.IDialog;
import com.hbw020.androidcustomizedialogandpopupwindow.presenter.SYDialog;
import com.lzy.okgo.model.Progress;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropFragment;
import com.yalantis.ucrop.UCropFragmentCallback;
import com.zsgeek.wisdchain.qutu.BaseActivity;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.customControl.ClearEditText;
import com.zsgeek.wisdchain.qutu.base.customControl.EmptyRecyclerView;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.BaseModel;
import com.zsgeek.wisdchain.qutu.base.model.DrawableBean;
import com.zsgeek.wisdchain.qutu.base.model.StringModel;
import com.zsgeek.wisdchain.qutu.popup.dialog.DialogUtil;
import com.zsgeek.wisdchain.qutu.tools.ImageUtils;
import com.zsgeek.wisdchain.qutu.tools.LogUtil;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.view.MainActivity;
import com.zsgeek.wisdchain.qutu.view.home.adapter.C2cAppealAgainstPicAdapter;
import com.zsgeek.wisdchain.qutu.view.home.recyclerview.GridSpacesItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 发布笔记
 */

public class PostNotesActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, UCropFragmentCallback {

    @BindView(R.id.title_et)
    ClearEditText titleEt;
    @BindView(R.id.content_et)
    ClearEditText contentEt;
    @BindView(R.id.set_connect_rl)
    RelativeLayout setConnectRl;
    @BindView(R.id.read_rule_rl)
    RelativeLayout readRuleRl;
    @BindView(R.id.ccg_btn)
    TextView ccgBtn;
    @BindView(R.id.fbbj_btn)
    TextView fbbjBtn;
    @BindView(R.id.rv_trade_list)
    EmptyRecyclerView mTradeRecyclerView;
    private List<DrawableBean> dataList = new ArrayList<>();
    private C2cAppealAgainstPicAdapter mAdapter;
    private final int SELECT_PHOTO = 0x200, TAKE_PHOTO = 0x202, WRITE_EXTERNAL_STORAGE = 0x203, RC_CAMERA_PERM = 0x204;
    private String adver_url = "";
    private int partId = -1;
    private String read_time = "", read_num = "", share_num = "", collect_num = "", comment_num = "", agree_num = "", total = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_post_notes;
    }

    @Override
    protected void initView() {
        setTitle("发布笔记");
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        dataList.add(new DrawableBean(DrawableBean.TYPE_ADD));
        if (dataList != null && dataList.size() > 0) {
            mTradeRecyclerView.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            mTradeRecyclerView.setAdapter(mAdapter = new C2cAppealAgainstPicAdapter(this, dataList));
            mTradeRecyclerView.addItemDecoration(new GridSpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin), false));
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                switch (view.getId()) {
                    case R.id.upload_data_iv:
                        if (dataList.get(position).getType() != DrawableBean.TYPE_ADD) {
                            ZoomPictureDialog(dataList.get(position).getPicturePath());
                        } else {
                            if (dataList.size() < 7) {
                                select_photo();
                            } else ToastHelper.showToast("最多上传6个附件");
                        }
//                        if (dataList.get(position).getType() == DrawableBean.TYPE_ADD) {
//                            if (dataList.size() < 7) {
//                                select_photo();
//                            } else ToastHelper.showToast("最多上传6个附件");
//                        } else ZoomPictureDialog(dataList.get(position).getPicturePath());
                        break;
                    case R.id.cancel_upload_data_iv:
                        adapter.remove(position);
                        break;
                }
            });
        }
    }

    @OnClick({R.id.set_connect_rl, R.id.read_rule_rl, R.id.advertisement_type_rl, R.id.ccg_btn, R.id.fbbj_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_connect_rl:
                startActivityForResult(new Intent(this, SetConnectActivity.class), 0x105);
                break;
            case R.id.read_rule_rl:
                startActivityForResult(new Intent(this, ReadRuleActivity.class), 0x106);
                break;
            case R.id.advertisement_type_rl:
                startActivityForResult(new Intent(this, AdvertisementTypeActivity.class), 0x107);
                break;
            case R.id.ccg_btn:
                addAdve(0);
                break;
            case R.id.fbbj_btn:
                addAdve(1);
                break;
        }
    }

    /**
     * 广告发布接口
     *
     * @param status 状态： 0-草稿，1-发布
     */
    private void addAdve(int status) {
        try {
            String title = titleEt.getText().toString().trim();
            if (TextUtils.isEmpty(title)) {
                ToastHelper.showToast("填写标题会获得更多的赞哦");
                return;
            }
            String content = contentEt.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                ToastHelper.showToast("添加正文");
                return;
            }
            if (TextUtils.isEmpty(adver_url)) {
                ToastHelper.showToast("请设置链接");
                return;
            }
            if (partId == -1) {
                ToastHelper.showToast("请选择广告类型");
                return;
            }
            if (TextUtils.isEmpty(total)) {
                ToastHelper.showToast("请设置阅读规则");
                return;
            }
            double parseDouble = Double.parseDouble(total);
            if (parseDouble <= 0) {
                ToastHelper.showToast("请设置阅读规则");
                return;
            }
            if (dataList.size() <= 0) {
                ToastHelper.showToast("至少上传一张图片");
                return;
            }
            String images = null;
            for (int i = 0; i < dataList.size(); i++) {
                if (i == 0) {
                    images = dataList.get(i).getPicturePath();
                } else {
                    images += "," + dataList.get(i).getPicturePath();
                }
            }
            addAdve(status, title, content, images);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 广告发布接口
     */
    private void addAdve(int status, String title, String content, String images) {
        DialogUtil.createLoadingDialog(this, null);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("images", "");
//        map.put("partId", "");
//        map.put("content", "");
//        map.put("read_num", "");
//        map.put("collect_num", "");
//        map.put("comment_num", "");
//        map.put("agree_num", "");
//        map.put("status", "");
//        map.put("total", "");
//        map.put("addr", "");
//        GsonUtil.createJson(map);
        new JsonRequest(new JsonRequestCallBack() {
            @Override
            public void showResult(Object object, String taskId) {
                if (object instanceof BaseModel) {
                    BaseModel dataModel = (BaseModel) object;
                    DialogUtil.closeLoadingDialog(PostNotesActivity.this);
                    if (dataModel.getCode() == 2000) {
                        ToastHelper.showToast(R.string.success);
                        SystemClock.sleep(500);
                        setResult(-1);
                        finish();
                    } else ToastHelper.showToast(dataModel.getMessage());
                }
            }

            @Override
            public void showError(String errorMsg, String taskId) {
                DialogUtil.closeLoadingDialog(PostNotesActivity.this);
                ToastHelper.showToast(errorMsg);
            }
        }).postJson(UrlPathHelper.getAdver() + "adver/addAdver?partId=" + partId + "&content=" + content
                + "&title=" + title + "&read_num=" + read_num + "&collect_num=" + collect_num + "&comment_num="
                + comment_num + "&agree_num=" + agree_num + "&status=" + status + "&total=" + total
                + "&addr=" + MainActivity.address + "&images=" + images + "&adver_url=" + adver_url
                + "&read_time=" + read_time + "&share_num=" + share_num, true, null, BaseModel.class);
    }

    private JsonRequestCallBack jsonRequestCallBack = new JsonRequestCallBack() {
        @Override
        public void showResult(Object object, String taskId) {
            if (object instanceof StringModel) {
                StringModel fileUploadModel = (StringModel) object;
                DialogUtil.closeLoadingDialog(PostNotesActivity.this);
                if (fileUploadModel.getCode() == 2000) {
                    dataList.add(new DrawableBean(null, (String) fileUploadModel.getData()));
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastHelper.showToast(fileUploadModel.getMessage());
                }
            }
        }

        @Override
        public void showError(String errorMsg, String taskId) {
            DialogUtil.closeLoadingDialog(PostNotesActivity.this);
            ToastHelper.showToast(errorMsg);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x101:
                    DialogUtil.closeLoadingDialog(PostNotesActivity.this);
                    ToastHelper.showToast((String) msg.obj);
                    break;
                case 0x102:
                    File file = (File) msg.obj;
                    new JsonRequest<>(jsonRequestCallBack).uploadFile(UrlPathHelper.getAdver() + "file/uploadImage",
                            "images", file, StringModel.class, new Consumer<Disposable>() {
                                @Override
                                public void accept(Disposable disposable) throws Exception {
                                    LogUtil.i("正在上传中...");
                                }
                            }, new Observer<Progress>() {
                                @Override
                                public void onSubscribe(Disposable d) {
//                                    addDisposable(d);
                                    LogUtil.i("上传进度：" + d.isDisposed());
                                }

                                @Override
                                public void onNext(Progress progress) {

                                    String downloadLength = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);
                                    String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
//                                    tvDownloadSize.setText(downloadLength + "/" + totalLength);
//                                    String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
//                                    tvNetSpeed.setText(String.format("%s/s", speed));
//                                    tvProgress.setText(numberFormat.format(progress.fraction));
//                                    pbProgress.setMax(10000);
//                                    pbProgress.setProgress((int) (progress.fraction * 10000));
                                    LogUtil.i("downloadLength:" + downloadLength + "/" + totalLength + ",进度:" + (int) (progress.fraction * 10000));
                                }

                                @Override
                                public void onError(Throwable e) {
                                    DialogUtil.closeLoadingDialog(PostNotesActivity.this);
                                    e.printStackTrace();
                                    LogUtil.i("上传出错," + e.getMessage());
                                }

                                @Override
                                public void onComplete() {
                                    LogUtil.i("上传完成");
                                }
                            });
                    break;
//                case 0x103:
//                    Glide.with(C2cAppealAgainstActivity.this)
//                            .load(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), "GuoBiTradeCropAuthenticationImage.jpg"))
//                            .diskCacheStrategy(DiskCacheStrategy.NONE)
//                            .into(imageView);
////                    Glide.with(ValidateIdentityActivity.this).load(profileModelDataBean.getAvatar()).diskCacheStrategy(DiskCacheStrategy.NONE).into(headPortraitIv);
//                    break;
            }
        }
    };

    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
            DialogUtil.createLoadingDialog(this, "图片压缩上传中...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        File saveFile = copyFileToDownloads(resultUri);
                        if (saveFile != null) {
                            Message message = handler.obtainMessage(0x102);
                            message.obj = saveFile;
                            handler.sendMessage(message);
                        }

//                int maxSize = ImageUtils.getMaxSize();
//                int requestSize = Math.min(300, maxSize);
//                final Bitmap selectPictureBitmap = ImageUtils.decodeSampledBitmapFromUri(this, resultUri, requestSize);
//                if (selectPictureBitmap != null)
//                    headPortraitIv.setImageBitmap(selectPictureBitmap);

                    } catch (Exception e) {
                        e.printStackTrace();
                        Message message = handler.obtainMessage(0x101);
                        message.obj = "图片保存失败";
                        handler.sendMessage(message);
                    }
                }
            }).start();

        } else {
            ToastHelper.showToast("无法检索裁剪的图像");
        }
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    private void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            LogUtil.e("handleCropError: ", cropError);
            ToastHelper.showToast(cropError.getMessage());
        } else {
            ToastHelper.showToast("Unexpected error");
        }
    }

    @Override
    public void loadingProgress(boolean showLoader) {
        supportInvalidateOptionsMenu();
    }

    @Override
    public void onCropFinish(UCropFragment.UCropResult result) {
        switch (result.mResultCode) {
            case RESULT_OK:
                handleCropResult(result.mResultData);
                break;
            case UCrop.RESULT_ERROR:
                handleCropError(result.mResultData);
                break;
        }
    }

    /**
     * 打开相册的方法
     */
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PHOTO);
    }

    /**
     * 从相册中获取图片
     */
    @AfterPermissionGranted(WRITE_EXTERNAL_STORAGE)
    public void select_photo() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            openAlbum();
        } else
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.rationale_external_storage),
                    WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        LogUtil.d("onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_PHOTO:
                    final Uri selectedUri = data.getData();
                    startCrop(selectedUri);
                    break;
                case UCrop.REQUEST_CROP:
                    handleCropResult(data);
                    break;
//                case TAKE_PHOTO:
//                    startCrop(pictureUri);
//                    break;
                case 0x105:
                    adver_url = data.getStringExtra("URL");
                    break;
                case 0x106:
                    read_time = data.getStringExtra("read_time");
                    read_num = data.getStringExtra("read_num");
                    share_num = data.getStringExtra("share_num");
                    agree_num = data.getStringExtra("agree_num");
                    comment_num = data.getStringExtra("comment_num");
                    total = data.getStringExtra("total");
                    break;
                case 0x107:
                    partId = data.getIntExtra("partId", -1);
                    break;
            }
        }
//        if (resultCode == UCrop.RESULT_ERROR) {
//            handleCropError(data);
//        }
    }

    private File copyFileToDownloads(Uri croppedFileUri) throws Exception {
        String downloadsDirectoryPath = UrlPathHelper.PATH_IMAGE;
//        String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(), croppedFileUri.getLastPathSegment());
        if (!new File(downloadsDirectoryPath).exists())
            LogUtil.createDipPath(downloadsDirectoryPath);

        String filename = croppedFileUri.getLastPathSegment();
        File saveFile = new File(downloadsDirectoryPath, filename);
        ImageUtils.saveFileToDownloads(croppedFileUri.getPath(), saveFile);
        return saveFile;
    }

    private void startCrop(@NonNull Uri uri) {
        if (uri != null) {
            UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), "GuoBiTradeCropAuthenticationImage.jpg"))).withAspectRatio(1f, 1f);
//        uCrop = basisConfig(uCrop);
            uCrop = advancedConfig(uCrop);
            uCrop.start(this);
        } else {
            ToastHelper.showToast(R.string.toast_cannot_retrieve_selected_image);
        }
    }

    /**
     * Sometimes you want to adjust more options, it's done via {@link UCrop.Options} class.
     *
     * @param uCrop - ucrop builder instance
     * @return - ucrop builder instance
     */
    private UCrop advancedConfig(@NonNull UCrop uCrop) {
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setCompressionQuality(90);
        options.setHideBottomControls(true);
        options.setFreeStyleCropEnabled(true);
        return uCrop.withOptions(options);
    }

    private void ZoomPictureDialog(String path) {
        new SYDialog.Builder(this)
                .setDialogView(R.layout.dialog_show_image)
                .setWindowBackgroundP(0.5f)
                .setAnimStyle(R.style.AnimUp)
                .setCancelableOutSide(true)
                .setBuildChildListener(new IDialog.OnBuildListener() {
                    @Override
                    public void onBuildChildView(final IDialog dialog, View view, int layoutRes) {
                        ImageView QrCodeIv = view.findViewById(R.id.recommendation_code_iv);
                        Glide.with(PostNotesActivity.this).load(path).into(QrCodeIv);
                        QrCodeIv.setOnClickListener(v -> dialog.dismiss());
                    }
                })
                .setScreenWidthP(1.0f)
                .setGravity(Gravity.CENTER).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
